<template>
    <div>
        <div class="buttons mb-2">
            <el-button type="primary" icon="plus" @click="showDispatch">分配</el-button>
        </div>

        <data-table :fields="tableFields" v-model="apps" ref="tableRef" />

        <el-dialog v-model="visible" title="分配应用" width="400px" destroy-on-close>
            <base-form :fields="dispatchFields" v-model="dispatchForm" ref="dispatchFormRef"></base-form>

            <template #footer>
                <el-button @click="visible = false">取消</el-button>
                <el-button type="primary" @click="dispatchApps">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { onMounted } from "vue";
import dataTable from "@/components/base-table/data-table.vue";

const { tenant } = defineProps({
    tenant: Object,
});

const apps = ref([]);
const visible = ref(false);
const dispatchFields = [
    {
        label: "应用",
        prop: "appIds",
        type: "select",
        options: () => app.https.get("/sys/tenant-app/not-dispatched", { tenantId: tenant.id }),
        required: true,
        multiple: true,
    },
    { label: "到期日期", prop: "expireDate", type: "datePicker" },
];
const dispatchForm = ref({});
const dispatchFormRef = ref();
const tableRef = ref();
const tableFields = [
    { label: "应用分类", prop: "app.categoryName" },
    { label: "应用名称", prop: "app.name" },
    { label: "应用编码", prop: "app.code", width: "120px" },
    { label: "过期日期", prop: "expireDate", width: "100px" },
    { label: "分配时间", prop: "createTime", width: "160px" },
    {
        label: "操作",
        prop: "operations",
        type: "operations",
        width: "120px",
        buttons: [
            {
                label: "移除",
                icon: "remove",
                type: "danger",
                action: (row) => {
                    app.confirm("确定移除当前记录？").then(() => {
                        app.https.del("/sys/tenant-app/delete/" + row.id).then(() => {
                            app.success();
                            loadApps();
                        });
                    });
                },
            },
        ],
    },
];

onMounted(loadApps);

function loadApps() {
    // 查询租户应用列表
    app.https.get("/sys/tenant-app/dispatched", { tenantId: tenant.id }).then((resp) => {
        apps.value = resp;
    });
}

function showDispatch() {
    dispatchForm.value = {};
    visible.value = true;
}

function dispatchApps() {
    dispatchFormRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https
            .post("/sys/tenant-app/add", { tenantId: tenant.id, appIds: dispatchForm.value.appIds, expireDate: dispatchForm.value.expireDate })
            .then(() => {
                app.success("操作成功");
                loadApps();
                visible.value = false;
            });
    });
}
</script>

<style lang="scss" scoped></style>
